# 封装数据库操作的SQL语句
import logging

import pymysql


class DBUtil():
    __conn = None
    host = '211.103.136.244'
    port = 7061
    user = "student"
    password = 'iHRM_student_2022'
    database = "ihrm"

    # 切换数据库，默认IHRM，可切换为TPshop
    @classmethod
    def chg_db(cls):
        cls.host = "localhost"
        cls.port = 3306
        cls.user = "root"
        cls.password = "123"
        cls.database = "test"

    # 创建连接
    @classmethod
    def __get_conn(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host=cls.host, port=cls.port, user=cls.user, password=cls.password,
                                         database=cls.database, charset='utf8')
        return cls.__conn

    # 关闭连接
    @classmethod
    def __discon(cls):
        if cls.__conn is not None:
            cls.__conn.close()
            cls.__conn = None

    # 查询一条记录
    @classmethod
    def select_one(cls, sql):
        res = None
        cursor = None
        try:
            cls.__conn = cls.__get_conn()
            cursor = cls.__conn.cursor()
            cursor.execute(sql)
            res = cursor.fetchone()
        except Exception as e:
            # print("查询错误：", e)
            logging.error("查询错误：", e)
        finally:
            cursor.close()
            cls.__discon()
            # print(res)
            return res

    # 增删改
    @classmethod
    def uid(cls, sql):
        cursor = None
        try:
            cls.__conn = cls.__get_conn()
            cursor = cls.__conn.cursor()
            cursor.execute(sql)
            logging.info(f"影响行数：{cls.__conn.affected_rows()}")
            cls.__conn.commit()
        except Exception as E:
            logging.error("修改错误：", E)
            cls.__conn.rollback()
        finally:
            cursor.close()
            cls.__discon()


if __name__ == '__main__':
    print(DBUtil.select_one("select * from students;"))
    DBUtil.uid("insert into students(name) values('韩信');")
